package net.projecteuler.prob;

import java.math.BigInteger;

public class Problem68 implements Runnable {

	private int[] ringArr = new int[10];
	private boolean[] checkArr = new boolean[11];
	private int idx = 0;
	private BigInteger maxString = BigInteger.ZERO;
	
	private int permuteCnt = 0;
	private int gonRingCnt = 0;
	
	@Override
	public void run() {
		for(int i = 0; i < 11; i++) checkArr[i] = false;
		
		permutate();
		System.out.println("permuteCnt " + permuteCnt);
		System.out.println("gonRingCnt " + gonRingCnt);
	}
	
	private void permutate(){
		if(idx == 10){
			permuteCnt++;
			checkGonRing();
		}
		
		for(int i = 1; i <= 10; i++){
			if(!checkArr[i]){
				ringArr[idx] = i;
				
				checkArr[i] = true;						
				idx++;
				permutate();
				checkArr[i] = false;
				idx--;
			}
		}
	}
	
	private void checkGonRing(){
		int sum = 0;
		
		for(int i = 0; i < 5; i++){
			int temp = ringArr[i] + ringArr[i+5] + ringArr[(i+1)%5 + 5];
			if(sum != 0 && sum != temp)
				return;
			else
				sum = temp;
		}
		
		gonRingCnt++;
				
		String str = "";
		int minIdx = 0;
		int minStartTemp = 99;
		for(int i = 0; i < 5; i++){
			if(minStartTemp > ringArr[i]){
				minIdx = i;
				minStartTemp = ringArr[i];
			}
		}
		
		for(int i = 0; i < 5; i++){
			int idxStart = (minIdx + i) % 5;
			str += Integer.toString(ringArr[idxStart]);
			str += Integer.toString(ringArr[idxStart+5]);
			str += Integer.toString(ringArr[(idxStart+1)%5 + 5]);
		}
		
		if(str.length() == 16){
			BigInteger big = new BigInteger(str);
			if(maxString.compareTo(big) == -1){
				maxString = big;
				System.out.println(maxString);
			}
		}
	}
	

}
